package com.xyauto.theme.base

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.xyauto.theme.base.vm.BaseViewModel
import java.lang.reflect.ParameterizedType


/**
 * Created by gongziyi on 2021/5/13 17:58.
 */
public abstract class BaseVMActivity<VM : BaseViewModel> : BaseActivity() {

    protected lateinit var viewModel: VM

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        createViewModel()
        registerUIChange()
    }


    private fun createViewModel() {
        viewModel = ViewModelProvider(this).get(getTClass())
        lifecycle.addObserver(viewModel)
    }

    /**
     * 注册 UI 事件
     */
    private fun registerUIChange() {
        viewModel.ui.showDialog.observe(this) {
            showLoadingDialog(it)
        }
        viewModel.ui.dismissDialog.observe(this) {
            dismissLoadingDialog()
        }
        viewModel.ui.errorEvent.observe(this) {
            showError(it.errMsg, it.code)
        }
    }


    /**
     * 获取泛型VM的实际类型
     * 如果基于BaseVM继续抽象 请确保VM泛型为泛型参数中最后一个
     */
    @Suppress("UNCHECKED_CAST")
    private fun getTClass(): Class<VM> {
        val parameterizedType = javaClass.genericSuperclass as ParameterizedType
        val typeArguments = parameterizedType.actualTypeArguments
        return typeArguments.last() as Class<VM>
    }

//
//    fun showMessageDialog(msg: String, title: String = "提示", showCancel: Boolean = true, cancel: (() -> Unit)? = null, confirm: (() -> Unit)? = null) {
//        MessageDialog.Builder(this)
//            .setTitle(title)
//            .setMessage(msg)
//            .showCancel(showCancel)
//            .setCancelListener {
//                it.dismiss()
//                cancel?.invoke()
//            }.setConfirmListener {
//                confirm?.invoke()
//            }
//            .show()
//    }


}